package com.itheima.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class FileClearTask {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MinioFileUtil minioFileUtil;

    /**
     * 定时清除minio中的垃圾数据  每隔5分钟一次
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void clearDiffData() {
        log.info("--------------定时垃圾扫描开始----------------");
        Set<String> difference = redisTemplate.opsForSet().difference("uploadImgUrl", "databaseImgUrl");
        if (difference != null && difference.size() > 0) {
            //有不同
            //从minio中删除
            difference.forEach(url -> {
                log.info("发现垃圾数据,文件名:{}",url);
                boolean success = minioFileUtil.remove(url);
                if(success)
                    log.info("删除成功！");
                else
                    log.error("删除失败！");
            });
        }
        //清除redis中两个key
        redisTemplate.delete("uploadImgUrl");
        redisTemplate.delete("databaseImgUrl");
        log.info("--------------定时垃圾扫描结束----------------");
    }
}
